import os
import shutil
from time import sleep
from decimal import Decimal, DivisionByZero, InvalidOperation
from django.core.serializers.json import DjangoJSONEncoder
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render, redirect
from .models import *
from django.db import transaction
from django.contrib.auth import login, logout
from django.core.validators import validate_email
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.contrib.auth import authenticate, login
from django.contrib.auth.hashers import check_password
from django.contrib.auth.hashers import make_password
from django.http import JsonResponse
from decimal import Decimal
from django.db.models import F

def index(request):
    if request.user.is_authenticated:
        if request.user.group_id == 1:
            return redirect('/manager')
        else:
            return redirect('/worker')

    return render(request, 'index.html')


def chat(request):
    return render(request, 'chat.html')


def user_login(request):
    if request.method == 'POST':
        username = request.POST.get('username', '').strip()
        password = request.POST.get('password', '').strip()
        next_url = request.POST.get('next', '')  # 获取next参数

        error_message = None

        if not username or not password:
            error_message = "请填写用户名和密码"
        else:
            try:
                user = User.objects.get(username=username)

                if check_password(password, user.password):
                    login(request, user)
                    if user.group_id == 1:  # 管理员
                        redirect_url = next_url if next_url else '/manager'
                        return redirect(redirect_url)
                    else:  # 员工 (group_id == 0)
                        redirect_url = next_url if next_url else '/worker'
                        return redirect(redirect_url)
                else:
                    error_message = "密码错误"
            except User.DoesNotExist:
                error_message = "用户名不存在"

        if error_message:
            return render(request, 'login.html', {
                'error_message': error_message,
                'next': next_url  # 将next参数传递回模板
            })

    # GET请求直接显示登录页面
    next_url = request.GET.get('next', '')  # 从GET参数获取next
    return render(request, 'login.html', {'next': next_url})





def user_logout(request):
    print("Logging out user...")
    logout(request)
    # 重定向到 `/fine-se` 页面
    return redirect('/fine-se')



def register(request):
    if request.method == 'POST':
        # 获取表单数据
        real_name = request.POST.get('real_name', '').strip()
        username = request.POST.get('username', '').strip()
        employee_id = request.POST.get('employee_id', '').strip()
        position = request.POST.get('position', '').strip()
        password = request.POST.get('password', '').strip()
        confirm_password = request.POST.get('confirm_password', '').strip()
        user_type = request.POST.get('user_type', 'employee')  # employee 或 admin
        agree_terms = request.POST.get('agree_terms') == 'on'
        email = request.POST.get('email', '').strip()

        # 验证数据
        error_message = None

        if not all([real_name, username, employee_id, password, confirm_password]):
            error_message = "请填写所有必填字段"
        elif password != confirm_password:
            error_message = "两次输入的密码不一致"
        elif not agree_terms:
            error_message = "请同意服务条款和隐私政策"
        elif User.objects.filter(username=username).exists():
            error_message = "该用户名已被注册"
        elif User.objects.filter(employee_id=employee_id).exists():
            error_message = "该工号已被注册"
        elif User.objects.filter(email=email).exists():
            error_message = "该邮箱已被注册"
        else:
            # 验证邮箱格式
            try:
                validate_email(email)
            except ValidationError:
                error_message = "请输入有效的邮箱地址"

        if error_message:
            return render(request, 'register.html', {
                'error_message': error_message,
                'real_name': real_name,
                'username': username,
                'employee_id': employee_id,
                'position': position,
            })

        # 使用事务确保数据一致性
        try:
            with transaction.atomic():
                # 确定用户组ID和描述
                group_id = 1 if user_type == 'admin' else 2
                group_description = 'manager' if group_id == 1 else 'worker'

                # 创建或获取用户组记录
                user_group, created = UserGroup.objects.get_or_create(
                    id=group_id,
                    defaults={'description': group_description}
                )

                # 创建用户记录
                user = User.objects.create(
                    username=username,
                    password=make_password(password),
                    full_name=real_name,
                    employee_id=employee_id,
                    position=position,
                    group_id=group_id,  # 直接设置group_id
                    email=email,
                )

                # 注册成功后重定向到登录页面
                return redirect('/login')

        except Exception as e:
            error_message = f"注册失败: {str(e)}"
            return render(request, 'register.html', {
                'error_message': error_message,
                'real_name': real_name,
                'username': username,
                'employee_id': employee_id,
                'position': position,
            })

    # GET请求显示注册页面
    return render(request, 'register.html')


def train(request):
    if request.user.is_authenticated:
        if request.user.group_id == 1:
            user_full_name = request.user.full_name
            user_id = request.user.id

            # 获取URL参数，判断是否是新建项目
            is_new_project = request.GET.get('new') == 'true'

            # 获取该用户参与的项目（通过UserProject表关联）
            user_projects = Project.objects.filter(userproject__user_id=user_id)

            # 构造符合格式的项目列表
            projects = [
                {
                    'id': project.id,
                    'name': project.name,
                    'start_date': project.created_at.date()
                }
                for project in user_projects
            ]

            # 如果是新建项目，添加一个临时项目
            if is_new_project:
                projects.append({'id': 'null', 'name': 'new_project', 'start_date': datetime.now().date()})

            selected_project_id = None
            selected_project_name = None

            return render(request, 'train.html', {
                'user_full_name': user_full_name,
                'projects': projects,
                'selected_project_id': selected_project_id,
                'selected_project_name': selected_project_name
            })
        else:
            return render(request, 'error.html', {'message': '您没有权限登录！'})
    else:
        return redirect('/login')


def create_project_and_assign_user(user_id, project_name):
    try:
        # 获取用户实例
        user = User.objects.get(id=user_id)

        # 创建 Project 实例
        project = Project.objects.create(
            name=project_name,
            created_by=user,
            created_at=timezone.now()
        )

        # 创建 UserProject 关系
        UserProject.objects.create(
            user=user,
            project=project
        )

        return project.id  # 或返回 project 对象也可以

    except User.DoesNotExist:
        raise ValueError(f"User with id {user_id} does not exist.")
    except Exception as e:
        raise Exception(f"Error creating project or assigning user: {str(e)}")

def update_project_name(user_id, project_id, project_name):
    try:
        # 校验该用户是否与该项目有关联
        if not UserProject.objects.filter(user_id=user_id, project_id=project_id).exists():
            raise PermissionError("该用户无权限修改此项目。")

        # 获取并更新项目名称
        project = Project.objects.get(id=project_id)
        project.name = project_name
        project.save()

        return True  # 表示更新成功

    except Project.DoesNotExist:
        raise ValueError(f"项目 ID 为 {project_id} 的项目不存在。")
    except User.DoesNotExist:
        raise ValueError(f"用户 ID 为 {user_id} 的用户不存在。")
    except Exception as e:
        raise Exception(f"更新项目名称失败: {str(e)}")

def save_models(user_id, project_id, rename_dict):
    """
    :param user_id: 用户 ID（未使用，但保留供后续权限控制等）
    :param project_id: 项目 ID
    :param rename_dict: 字典格式，key 为 epoch 数值（字符串），value 为用户重命名的模型名
    :return: 保存的模型信息列表
    """
    try:
        # 获取项目实例（确保项目存在）
        project = Project.objects.get(id=project_id)
        project_name = project.name

        saved_models = []

        # 遍历每个 epoch -> 新名称 的键值对
        for epoch_str, custom_name in rename_dict.items():
            epoch_file = f"{epoch_str}.pt"
            src_path = os.path.join('./model/model', epoch_file)

            if not os.path.exists(src_path):
                print(f"文件 {src_path} 不存在，跳过。")
                continue

            # 创建 ModelInfo 数据记录
            model_info = ModelInfo.objects.create(
                name=custom_name,
                project=project
            )

            # 新的文件名：使用 ModelInfo 的 id 命名
            new_file_name = f"{model_info.id}.pt"
            dest_path = os.path.join('../BIGCHUANGFILE/MODELS', new_file_name)

            # 创建目标目录（如果不存在）
            os.makedirs(os.path.dirname(dest_path), exist_ok=True)

            # 移动并重命名文件
            shutil.move(src_path, dest_path)

            saved_models.append({
                "id": model_info.id,
                "name": custom_name,
                "path": dest_path
            })

        return saved_models

    except Project.DoesNotExist:
        raise ValueError(f"项目 ID 为 {project_id} 的项目不存在。")
    except Exception as e:
        raise Exception(f"保存模型过程中出错: {str(e)}")

def handle_prediction_request(request):
    if request.method == 'POST':
        current_project_name = request.POST.get('current_project_name')
        current_project_id = request.POST.get('current_project_id')
        print(f"当前项目名称: {current_project_name}")
        print(f"当前项目id: {current_project_id}")
        username = request.POST.get('username')
        user_id = request.user.id
        print("user_id:",user_id)
        selected_epochs = json.loads(request.POST.get('selected_epochs'))
        #原格式[{'epoch': 5, 'name': 'my_model'}, {'epoch': 10, 'name': 'Epochs(10)'}]
        selected_epochs = {str(item['epoch']): item['name'] for item in selected_epochs}
        #转换格式为{"5": "my_model","10": "Epochs(10)"}

        # 在控制台打印接收到的数据
        print(f"收到保存请求 - 用户名: {username}, 选择的epochs和重命名: {selected_epochs}")

        #创建项目&对比是否为已有项目
        if not current_project_id:
            try:
                current_project_id = create_project_and_assign_user(user_id, current_project_name)
            except Exception as e:
                # 处理异常
                print(f"创建项目出错：{e}")
        else:
            try:
                success = update_project_name(user_id, current_project_id, current_project_name)
                if success:
                    print("项目更新成功")
            except Exception as e:
                print(f"更新项目名称出错：{e}")
        #保存模型&重命名
        try:
            result = save_models(user_id, current_project_id, selected_epochs)
            print("保存结果：", result)
        except Exception as e:
            print("保存模型出错：", e)

        return JsonResponse({'status': 'success', 'message': 'Request received by views.py'})
    return JsonResponse({'status': 'error', 'message': 'Invalid request method'})


def predict(request):
    if request.user.is_authenticated:
        if request.user.group_id == 1:
            user_full_name = request.user.full_name
            user_id = request.user.id


            # 获取该用户参与的项目（通过UserProject表关联）
            user_projects = Project.objects.filter(userproject__user_id=user_id)

            # 构造符合格式的项目列表
            projects = [
                {
                    'id': project.id,
                    'name': project.name,
                    'start_date': project.created_at.date()
                }
                for project in user_projects
            ]

            print(projects)

            selected_project_id = None
            selected_project_name = None

            return render(request, 'predict.html', {
                'user_full_name': user_full_name,
                'projects': projects,
                'selected_project_id': selected_project_id,
                'selected_project_name': selected_project_name
            })
        else:
            return render(request, 'error.html', {'message': '您没有权限登录！'})
    else:
        return redirect('/login')


def result(request):
    return render(request, 'result.html')


@csrf_exempt
def forgot(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        email = request.POST.get('email')

        try:
            user = User.objects.get(username=username, email=email)
            return JsonResponse({
                'success': True,
                'username': user.username,
                'message': '验证成功'
            })
        except User.DoesNotExist:
            return JsonResponse({
                'success': False,
                'message': '用户名和邮箱不匹配'
            })

    # 如果是GET请求，显示忘记密码页面
    return render(request, 'forgot.html')


@csrf_exempt
def reset(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        new_password = request.POST.get('new_password')
        confirm_password = request.POST.get('confirm_password')

        if new_password != confirm_password:
            return JsonResponse({
                'success': False,
                'message': '两次输入的密码不匹配'
            })

        if len(new_password) < 6:
            return JsonResponse({
                'success': False,
                'message': '密码长度不能少于6个字符'
            })

        try:
            user = User.objects.get(username=username)
            user.password = make_password(new_password)
            user.save()
            return JsonResponse({
                'success': True,
                'message': '密码重置成功'
            })
        except User.DoesNotExist:
            return JsonResponse({
                'success': False,
                'message': '用户不存在'
            })

    return JsonResponse({
        'success': False,
        'message': '无效的请求方法'
    })

def content(request):
    return render(request, 'content.html')

def trainresult(request):
    return render(request, 'trainresult.html')


def predictchat(request):
    if request.method == 'POST':
        # 获取项目 ID 和名称
        project_id = request.POST.get('project_id')
        project_name = request.POST.get('project_name')

        print(f"接收项目数据 - ID: {project_id}, 名称: {project_name}")

        # 查询数据库中该项目的所有模型
        models = ModelInfo.objects.filter(project_id=project_id).order_by('-created_at')

        # 构造 epoch_data 格式
        epoch_data = [{'id': model.id, 'name': model.name} for model in models]

        if not epoch_data:
            epoch_data = [{'id': 0, 'name': '暂无可用模型'}]

        print(f"接收项目数据 - ID: {project_id}, 名称: {project_name}")

        # 返回渲染后的HTML而不是JSON
        return JsonResponse({
            'status': 'success',
            'message': '项目数据已接收',
            'epoch_data': epoch_data,
            'project_id': project_id,
            'project_name': project_name
        })

    if request.method == 'GET':
        # 初始GET请求返回空页面
        return render(request, 'predictchat.html', {
            'epoch_data': [],
            'username': request.user.username,
            'is_ajax': False
        })


from datetime import datetime, timedelta


def manager(request):
    if request.user.is_authenticated:
        if request.user.group_id == 1:

            user_full_name = request.user.full_name
            user_id = request.user.id

            # 获取该用户参与的所有项目
            user_projects = UserProject.objects.filter(user=request.user).select_related('project')
            project_data = []

            for up in user_projects:
                project = up.project
                # 计算项目进度（完成的子项目 / 总子项目）
                if project.subproject_count:
                    project_progress = round((project.completed_subproject / project.subproject_count) * 100, 2)
                else:
                    project_progress = 0.0

                # 构造数据
                project_data.append({
                    'id': project.id,
                    'name': project.name,
                    'start_date': project.created_at.date(),
                    'project_progress': project_progress,
                })

                print(project_data)

            return render(request, 'manager.html', {
                'user_full_name': user_full_name,
                'projects': project_data
            })

        else:
            return render(request, 'error.html', {'message': '您没有权限登录！'})
    else:
        return redirect('/login')

@csrf_exempt
def worker(request):
    if request.user.is_authenticated:
        if request.user.group_id == 2:
            if request.method == 'POST':
                try:
                    data = json.loads(request.body)
                    if data.get('action') == 'report_progress':
                        subproject_id = data.get('subproject_id')
                        try:
                            subproject = SubProject.objects.select_related('project').get(id=subproject_id)
                            prediction = PredictionResult.objects.get(subproject=subproject)

                            # 增加 progress 值（确保不会超过100）
                            subproject.progress = min(subproject.progress + Decimal('0.10'), Decimal('100.00'))

                            # 检查是否超过 predicted_effort 且尚未标记完成
                            if not subproject.is_completed and subproject.progress >= prediction.predicted_effort:
                                subproject.is_completed = True
                                # 项目已完成子项目数量 +1
                                subproject.project.completed_subproject = F('completed_subproject') + 1
                                subproject.project.save()

                            subproject.save()

                            return JsonResponse({
                                'status': 'success',
                                'message': '进度更新成功'
                            })

                        except SubProject.DoesNotExist:
                            return JsonResponse({
                                'status': 'error',
                                'message': '未找到指定的子任务'
                            })
                        except PredictionResult.DoesNotExist:
                            return JsonResponse({
                                'status': 'error',
                                'message': '未找到该子任务的预测结果'
                            })
                except json.JSONDecodeError:
                    return JsonResponse({
                        'status': 'error',
                        'message': '无效的请求数据'
                    }, status=400)


            user_full_name = request.user.full_name
            user_email = request.user.email
            user_id = request.user.id

            # 获取用户参与的所有项目（UserProject -> Project）
            user_projects = Project.objects.filter(userproject__user_id=user_id)

            project_data = []
            for project in user_projects:
                # 计算项目进度百分比
                if project.subproject_count:
                    project_progress = round((project.completed_subproject / project.subproject_count) * 100, 2)
                else:
                    # 无预测数据或除 0 等问题，保留默认 0.0
                    project_progress = 0.0

                # 获取该用户参与的该项目下的子项目
                user_subprojects = SubProject.objects.filter(
                    usersubproject__user_id=user_id,
                    project=project
                )

                subproject_list = []
                for sp in user_subprojects:
                    # 默认子项目进度百分比
                    sub_progress_percent = 0.0

                    try:
                        predicted_effort = sp.prediction.predicted_effort  # 关联 PredictionResult 表
                        if predicted_effort > 0:
                            sub_progress_percent = round((sp.progress / predicted_effort) * 100, 2)
                        if sub_progress_percent > 100:
                            sub_progress_percent = 100
                    except (AttributeError, DivisionByZero, InvalidOperation):
                        # 无预测数据或除 0 等问题，保留默认 0.0
                        pass

                    subproject_list.append({
                        'subproject_id': sp.id,
                        'subproject_content': sp.content,
                        'subproject_progress': float(sub_progress_percent)
                    })

                project_data.append({
                    'project_id': project.id,
                    'project_name': project.name,
                    'created_at': project.created_at.date(),
                    'project_progress': float(project_progress),
                    'subprojects': subproject_list
                })

            print("员工项目和子项目:", project_data)
            #示例格式： [{'project_id': 1, 'project_name': 'project1', 'created_at': datetime.date(2025, 4, 15), 'project_progress': 0.0, 'subprojects': [{'subproject_id': 2, 'subproject_content': 'Fix EventsResourceIT.testEventPostandGet', 'subproject_progress': 78.74}, {'subproject_id': 5, 'subproject_content': 'Limit not honored on subsequent requests with cursors', 'subproject_progress': 0.0}]}]

            return render(request, 'worker.html', {
                'user_full_name': user_full_name,
                'user_email': user_email,
                'project_data': json.dumps(project_data, cls=DjangoJSONEncoder)  # 使用Django的JSON编码器处理日期
            })
        else:
            # 如果是管理员，返回权限提示
            return render(request, 'error.html', {'message': '您没有权限登录！'})
    else:
        # 如果用户未登录，返回登录提示
        return redirect('/login')  # 假设你有登录页面


@csrf_exempt  # 如果你前端用 AJAX 且未传 csrf_token，临时用这个避免 CSRF 错误（注意安全性）
def rename(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            action = data.get('action')

            if action == 'rename_project':
                project_id = data.get('project_id')
                new_name = data.get('new_name')
                print(new_name)
                print(project_id)

                # 简单校验
                if not project_id or not new_name:
                    return JsonResponse({
                        'status': 'error',
                        'message': '项目ID或新名称不能为空'
                    })

                # 获取项目
                try:
                    project = Project.objects.get(id=project_id)
                except Project.DoesNotExist:
                    return JsonResponse({
                        'status': 'error',
                        'message': '项目不存在'
                    })

                # 可选：检查是否当前用户创建的项目
                if request.user != project.created_by:
                    return JsonResponse({
                        'status': 'error',
                        'message': '无权限修改该项目'
                    })

                # 修改并保存
                project.name = new_name
                project.save()

                return JsonResponse({
                    'status': 'success',
                    'message': '项目重命名成功'
                })

        except Exception as e:
            return JsonResponse({
                'status': 'error',
                'message': str(e)
            })

    return JsonResponse({
        'status': 'error',
        'message': '仅支持POST请求'
    })


from django.views.decorators.csrf import csrf_exempt
import json


@csrf_exempt
def join_project(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            invite_code = data.get('invite_code')
            user = request.user

            if not invite_code:
                return JsonResponse({'status': 'error', 'message': '邀请码不能为空'})

            if not user.is_authenticated:
                return JsonResponse({'status': 'error', 'message': '用户未登录'})

            # 查找项目
            try:
                project = Project.objects.get(id=invite_code)
            except Project.DoesNotExist:
                return JsonResponse({'status': 'error', 'message': '项目不存在'})

            # 检查是否已加入
            if UserProject.objects.filter(user=user, project=project).exists():
                return JsonResponse({'status': 'error', 'message': '你已经加入了该项目'})

            # 创建用户-项目关系
            UserProject.objects.create(user=user, project=project)

            return JsonResponse({'status': 'success', 'message': '加入项目成功'})

        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)})

    return JsonResponse({'status': 'error', 'message': '仅支持 POST 请求'})


from django.views.decorators.http import require_http_methods


@require_http_methods(["GET", "POST"])
def assigncontent(request):
    user_id = request.user.id

    if request.method == 'POST' and request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        try:
            data = json.loads(request.body)
            project_id = data.get('project_id')

            # 验证权限
            if not UserProject.objects.filter(user_id=user_id, project_id=project_id).exists():
                return JsonResponse({'success': False, 'error': '无权访问此项目'}, status=403)

            # 获取子项目信息
            subprojects = SubProject.objects.filter(
                project_id=project_id
            ).annotate(
                predicted_effort=models.Subquery(
                    PredictionResult.objects.filter(
                        subproject_id=models.OuterRef('id')
                    ).values('predicted_effort')[:1]
                )
            ).values('id', 'content', 'predicted_effort')

            # 2. 获取usergroup_id=1的用户列表
            users = User.objects.filter(
                group_id=2,
                userproject__project_id=project_id
            ).values('id', 'full_name')
            print('成功获取到用户数据:', len(users))
            # 格式化用户数据
            formatted_users = [{
                'id': user['id'],
                'full_name': user['full_name']
            } for user in users]
            if not formatted_users:
                print("无符合员工")
            else:
                print(formatted_users)
            return JsonResponse({
                'success': True,
                'project_id': project_id,
                'subprojects': list(subprojects),
                'users': list(formatted_users)
            })

        except Exception as e:
            return JsonResponse({'success': False, 'error': str(e)}, status=500)

    # GET请求处理
    user_projects = UserProject.objects.filter(user_id=user_id).select_related('project')

    # 准备初始数据
    context = {
        'all_project': [
            {
                'project_id': up.project.id,
                'project_name': up.project.name
            }
            for up in user_projects
        ],
        # 初始化空数据，将通过AJAX填充
        'subprojects': [],
        'users': [],
        'selected_project_id': None
    }

    # 如果通过GET请求指定了project_id，则预加载数据
    if 'project_id' in request.GET:
        project_id = request.GET['project_id']
        context['selected_project_id'] = project_id

        # 获取子项目
        subprojects = SubProject.objects.filter(
            project_id=project_id
        ).annotate(
            predicted_effort=models.Subquery(
                PredictionResult.objects.filter(
                    subproject_id=models.OuterRef('id')
                ).values('predicted_effort')[:1]
            )
        ).values('id', 'content', 'predicted_effort')
        context['subprojects'] = list(subprojects)

        # 获取用户
        users = User.objects.filter(
            group_id=1,
            userproject__project_id=project_id
        ).values('id', 'full_name')
        context['users'] = list(users)

    return render(request, 'assigncontent.html', context)

def assign(request):
    if request.user.is_authenticated:
        if request.user.group_id == 1:
            user_full_name = request.user.full_name  # 获取当前登录用户的 full_name
            return render(request, 'assign.html', {
                'user_full_name': user_full_name,
            })
        else:
            # 如果是员工，返回权限提示
            return render(request, 'error.html', {'message': '您没有权限登录！'})
    else:
        # 如果用户未登录，返回登录提示
        return redirect('/login')



def save_results(request):
    if request.method == 'POST':
        project_id = request.POST.get('project_id')
        print(f"Received project_id: {project_id}")

        # 确保项目存在
        try:
            project = Project.objects.get(id=project_id)
        except Project.DoesNotExist:
            return JsonResponse({'status': 'error', 'message': 'Project not found'}, status=404)

        # 获取目录下最新的文件
        folder_path = './model/pred_output/'
        try:
            files = sorted(
                [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))],
                key=lambda x: os.path.getmtime(os.path.join(folder_path, x)),
                reverse=True
            )
            if not files:
                return JsonResponse({'status': 'error', 'message': 'No prediction file found'}, status=404)
            latest_file_path = os.path.join(folder_path, files[0])
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': f'Error reading directory: {e}'}, status=500)

        # 读取文件并解析为子项目
        try:
            with open(latest_file_path, 'r', encoding='utf-8') as f:
                lines = [line.strip() for line in f if line.strip()]

            if len(lines) % 2 != 0:
                return JsonResponse({'status': 'error', 'message': 'Invalid prediction file format'}, status=400)

            total_workload = Decimal('0.00')
            subproject_counter = 0

            for i in range(0, len(lines), 2):
                content = lines[i]
                effort_line = lines[i + 1]

                if "Predicted Workload:" in effort_line:
                    effort_str = effort_line.split("Predicted Workload:")[1].strip().strip("[]")
                    try:
                        predicted_effort = Decimal(effort_str)
                        total_workload += predicted_effort
                    except Exception:
                        continue
                else:
                    continue

                # 创建子项目及预测
                subproject = SubProject.objects.create(project=project, content=content)
                PredictionResult.objects.create(subproject=subproject, predicted_effort=predicted_effort)
                subproject_counter += 1

            # 更新项目总工作量与子项目数量
            project.total_workload = total_workload
            project.subproject_count = subproject_counter
            project.save()

        except Exception as e:
            return JsonResponse({'status': 'error', 'message': f'Error processing file: {e}'}, status=500)

        return JsonResponse({'status': 'success', 'project_id': project_id})

    return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=400)

@require_http_methods(["POST"])
def save_assign(request):
    try:
        print("\n=== 收到分配请求 ===")
        print("原始请求体:", request.body)

        data = json.loads(request.body)
        subtask_id = data.get('subtask_id')
        employee_ids = data.get('employee_ids', [])

        print("子任务ID:", subtask_id)
        print("员工ID列表:", employee_ids)

        subtask_id = int(subtask_id)
        employee_ids = [int(eid) for eid in employee_ids]

        subproject = SubProject.objects.get(id=subtask_id)

        # 当前数据库中这个子任务的所有关联用户ID
        existing_assignments = UserSubProject.objects.filter(subproject=subproject)
        existing_user_ids = set(existing_assignments.values_list('user_id', flat=True))

        new_user_ids = set(employee_ids)

        # ➤ 要删除的用户（已存在但这次未勾选）
        to_remove_ids = existing_user_ids - new_user_ids
        UserSubProject.objects.filter(subproject=subproject, user_id__in=to_remove_ids).delete()

        # ➤ 添加新用户（只添加原本不存在的）
        created_count = 0
        for user_id in new_user_ids:
            _, created = UserSubProject.objects.get_or_create(
                user_id=user_id,
                subproject=subproject
            )
            if created:
                created_count += 1

        return JsonResponse({
            'success': True,
            'status': 'assigned_updated',
            'subtask_id': subtask_id,
            'assigned_total': len(new_user_ids),
            'added_count': created_count,
            'removed_count': len(to_remove_ids)
        })

    except Exception as e:
        print("处理请求时出错:", str(e))
        return JsonResponse({
            'success': False,
            'status': 'error',
            'message': str(e)
        }, status=400)


@require_http_methods(["POST"])
@csrf_exempt
def son_task(request):
    if not request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        return JsonResponse({'status': 'error', 'message': '非法请求'}, status=400)

    try:
        data = json.loads(request.body)
        subtask_id = data.get('subtask_id')

        print(f"\n=== 收到子任务请求 ===")
        print(f"子任务ID: {subtask_id}")
        print(f"请求用户: {request.user.username}")

        # 查询被分配到该子任务，且用户组为 2 的员工
        assigned_users = User.objects.filter(
            usersubproject__subproject_id=subtask_id,
            group_id=2
        ).values('id', 'full_name')

        # 转为列表（QuerySet -> list of dicts）
        assigned_list = list(assigned_users)
        print("已选择的员工：", assigned_list)
        sleep(0.1)
        return JsonResponse({
            'status': 'success',
            'subtask_id': subtask_id,
            'assigned_users': assigned_list
        })

    except Exception as e:
        print(f"处理子任务请求时出错: {str(e)}")
        return JsonResponse({
            'status': 'error',
            'message': str(e)
        }, status=500)


from django.shortcuts import render
from .models import Project, UserProject

@require_http_methods(["GET", "POST"])
def monitor(request):
    if not request.user.is_authenticated:
        return redirect('/login')

    # 处理AJAX请求
    if request.method == 'POST' and request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        project_id = request.POST.get('project_id')

        try:
            project = Project.objects.get(id=project_id)
        except Project.DoesNotExist:
            return JsonResponse({'status': 'error', 'message': '项目不存在'}, status=404)

        subprojects_data = []

        subprojects = SubProject.objects.filter(project=project).select_related('prediction')
        print(subprojects)

        for sub in subprojects:
            # 获取预测工作量
            predicted_effort = sub.prediction.predicted_effort if hasattr(sub, 'prediction') else None

            current_effort = sub.progress  # 暂时用 progress 字段当作工作量百分比来源

            # 如果存在预测工作量，则计算进度百分比
            progress_percent = 0
            if predicted_effort and predicted_effort > 0:
                progress_percent = round(float(current_effort) / float(predicted_effort) * 100, 2)
                if progress_percent > 100: progress_percent = 100

            # 获取参与的员工
            users = User.objects.filter(usersubproject__subproject=sub).values_list('full_name', flat=True)

            subprojects_data.append({
                'id': sub.id,
                'name': sub.content,
                'progress': progress_percent,
                'members': list(users)
            })
        # print(subprojects_data)
        return JsonResponse({'status': 'success', 'subprojects': subprojects_data})

    # 原始GET请求处理逻辑
    user = request.user
    user_projects = UserProject.objects.filter(user=user).select_related('project')

    project_list = []
    for up in user_projects:
        project = up.project
        if project.subproject_count:
            progress = round((project.completed_subproject / project.subproject_count) * 100, 2)
        else:
            progress = 0.0

        project_list.append({
            'project_id': project.id,
            'project_name': project.name,
            'created_at': project.created_at.strftime('%Y-%m-%d'),
            'total_workload': float(project.total_workload),
            'project_progress': progress
        })

    return render(request, 'monitor.html', {
        'projects': project_list
    })

def monitorframe(request):
    if request.user.is_authenticated:
        if request.user.group_id == 1:
            user_full_name = request.user.full_name  # 获取当前登录用户的 full_name
            return render(request, 'monitorframe.html', {
                'user_full_name': user_full_name,
            })
        else:
            # 如果是员工，返回权限提示
            return render(request, 'error.html', {'message': '您没有权限登录！'})
    else:
        # 如果用户未登录，返回登录提示
        return redirect('/login')
